package net.betou.common.util;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

/**
 * 提供数据判断的类
 * 
 * @author 叶装装
 * 
 */
public final class DataCheckUtils{
	
	public static final String IMG_FORMAT = "jpg|jpeg|gif|png";
	
	public static boolean isImage( String ext ){
		if( StringUtils.isBlank( ext ) ){
			return false;
		}
		
		Pattern pattern = Pattern.compile( IMG_FORMAT, Pattern.CASE_INSENSITIVE);
		
    	Matcher matcher = pattern.matcher( ext );
    	
    	pattern = null;
    	
    	return matcher.matches( );
	}
	
	public static String [] validSuffixAndName( String fileName, String regex ){
		
		if( StringUtils.isBlank ( fileName ) || StringUtils.isBlank ( regex )){
			return null;
		}
		
		int lastIndex = fileName.lastIndexOf ( File.separator );

		fileName = lastIndex == -1 ? fileName : fileName.substring ( lastIndex + 1, fileName.length ( ) );
		
		if( regex.contains ( "," )){
			regex = regex.replace ( ",", "|" );
		}
		String name = fileName;
		
		int pointIndex = fileName.lastIndexOf(".");
		fileName = pointIndex != -1 ? fileName.substring(pointIndex + 1, fileName.length()) : fileName;
    	
    	Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    		
    	Matcher matcher = pattern.matcher( fileName );
    	
    	pattern = null;
    	
    	String suffix = matcher.matches() ? matcher.group() : null;
    	
    	return new String[]{suffix, name};
		
		
	}
	
	/**
	 * 判断是否为空或者空字符串
	 * 
	 * @param obj
	 * @return
	 */
	public static boolean isEmpty( Object obj, boolean trim ) {
		if( obj == null ){
			return true;
		}
		String str = obj.toString( );

		if( trim ){
			str = StringUtils.trim( str );
		}

		if( StringUtils.isBlank( str ) ){
			return true;
		}

		return false;

	}

	/**
	 * 判断是否是数字
	 * 
	 * @param num
	 * @return
	 */
	public static boolean isNum( Object num ) {
		if( num == null ){
			return false;
		}
		if( "".equals( num ) ){
			return false;
		}

		String regex = "^\\d+$";

		return num.toString( ).matches( regex );
	}
}
